using System;
using System.Collections;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Insight21.SearchContext;
using PHSRAG.Utility;
using Constants = PHSRAG.Insight21.InsightUtilities.Constants;
using SubNavigation = PHSRAG.Insight21.InsightWebControls.AgreementsSubNavigation;
using DetailsSubNavigation = PHSRAG.Insight21.InsightWebControls.AgreementDetailsSubNavigation;
using Helper = PHSRAG.WebControls.Helper;

namespace PHSRAG.Insight21.Agreements
{
    /// <summary>
    /// The BudgetBreakdown page displays budget information for a combination of category/account.
    /// </summary>
    public partial class BudgetBreakdownPage : NoCachePage
    {
        #region Private Types

        private enum ColumnIndex
        {
            FundNumber,
            BudgetAmount,
            Title,
            ProjectStartDate,
            ProjectEndDate,
            BudgetStartDate,
            BudgetEndDate,
            SponsorName,
            PIName
        }

        #endregion

        #region Constants

        private const string CurrentPageIndexKey = "currentPageIndex_00381C01-54D8-4846-9A91-CABFE38B39B7";
        private const string PageCacheKey = "BudgetBreakdown_00381C01-54D8-4846-9A91-CABFE38B39B7";
        private const string SearchCriteriaVersionKey = "SearchCriteriaVersion_00381C01-54D8-4846-9A91-CABFE38B39B7";

        #endregion

        #region Instance Variables (Private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;

        #endregion

        #region Private Properties

        /// <summary>
        /// Get a loaded BudgetBreakdown object based on the current search criteria. The invoking page chooses not to pass the
        /// filter criteria (such as GL post date, category ID, etc.) through the search criteria, and instead passes them
        /// through a dictionary. All we do is simply stick those into a cloned search criteria and let the business object
        /// load based on taht criteria.
        /// </summary>
        private BudgetBreakdowns BudgetBreakdowns
        {
            get
            {
                CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                SearchCriteria searchCriteria = searchContext.GetSearchCriteria(Page.Request.Url.ToString());
                int searchVersion = searchCriteria.Version;

                BudgetBreakdowns breakdowns =
                    ResultsCache.GetObject(cachePolicy, BudgetBreakdowns.CacheKey) as BudgetBreakdowns;
                if ((breakdowns == null) || (searchVersion != SearchCriteriaVersion))
                {
                    if (null != breakdowns)
                    {
                        ResultsCache.PurgeObject(cachePolicy);
                    }
                    breakdowns = new BudgetBreakdowns();

                    SearchCriteria clonedSearchCriteria = searchCriteria.Clone();

                    clonedSearchCriteria[Constants.GLPostAsOfDateKey] = GLPostAsOfDate.ToString();
                    clonedSearchCriteria[Constants.CategoryIDKey] = CategoryID.ToString();
                    clonedSearchCriteria[Constants.AccountNumberKey] = AccountNumber;
                    if (DetailsFlag)
                    {
                        clonedSearchCriteria[Constants.FundIDKey] = FundNumber;
                    }
                    clonedSearchCriteria[Constants.TransactionStartDateKey] = (BudgetStartDate != string.Empty) ? BudgetStartDate : null;
                    clonedSearchCriteria[Constants.TransactionEndDateKey] = (BudgetEndDate != string.Empty) ? BudgetEndDate : null;
                    clonedSearchCriteria[Constants.DetailsKey] = DetailsFlag.ToString();
                    clonedSearchCriteria[Constants.CumulativeKey] = CumLevel.ToString();
                    breakdowns.Search(Session.SessionID, clonedSearchCriteria);

                    ResultsCache.SetObject(cachePolicy, BudgetBreakdowns.CacheKey, breakdowns);

                    SearchCriteriaVersion = searchVersion;
                }

                return breakdowns;
            }
        }

        /// <summary>
        /// Get/Set the category ID for which the breakdowns are loaded.
        /// </summary>
        private int CategoryID
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                if ((h == null) || (h[Keys.CategoryIDKey] == null))
                {
                    throw new Exception("Budget breakdown page requires the Category ID to be specified");
                }
                return (int) h[Keys.CategoryIDKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[Keys.CategoryIDKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get/Set the DetailsFlag for which the breakdowns are loaded.
        /// </summary>
        private bool DetailsFlag
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                if ((h == null) || (h[Keys.DetailsKey] == null))
                {
                    throw new Exception("Budget breakdown page requires the DetailsFlag to be specified");
                }
                return (bool) h[Keys.DetailsKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[Keys.DetailsKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get/Set the account number for which the breakdowns are loaded.
        /// </summary>
        private string AccountNumber
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[Keys.AccountNumberKey] == null) ? null : (string) h[Keys.AccountNumberKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[Keys.AccountNumberKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get/Set the current page within the datagrid for display. This information persists across page loads.
        /// </summary>
        private int CurrentPageIndex
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[CurrentPageIndexKey] == null) ? 0 : (int) h[CurrentPageIndexKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[CurrentPageIndexKey] = value;
                dataGrid.CurrentPageIndex = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get/Set the fund number for which the breakdowns are loaded.
        /// </summary>
        public string FundNumber
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[Keys.FundNumberKey] == null) ? null : (string) h[Keys.FundNumberKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[Keys.FundNumberKey] = (value == string.Empty) ? null : value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get/Set the GL Post-as-of date which the breakdowns are loaded.
        /// </summary>
        public DateTime GLPostAsOfDate
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                if ((h == null) || (h[Constants.GLPostAsOfDateKey] == null))
                {
                    throw new Exception("Budget breakdown page requires the GLPostAsOfDate to be specified");
                }
                return (DateTime) h[Constants.GLPostAsOfDateKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[Constants.GLPostAsOfDateKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get/Set the budget start date date which the breakdowns are loaded.
        /// </summary>
        public string BudgetStartDate
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[Keys.BudgetStartDateKey] == null) ? string.Empty : (string) h[Keys.BudgetStartDateKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[Keys.BudgetStartDateKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get/Set the budget end date date which the breakdowns are loaded.
        /// </summary>
        public string BudgetEndDate
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[Keys.BudgetEndDateKey] == null) ? string.Empty : (string) h[Keys.BudgetEndDateKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[Keys.BudgetEndDateKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Get/Set the CumLevel used to determine if we are returning a cumulative report.
        /// </summary>
        public int CumLevel
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[Keys.CumulativeKey] == null) ? 0 : (int) h[Keys.CumulativeKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[Keys.CumulativeKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        /// <summary>
        /// Gets/sets an integer value indicating the search criteria version. 
        /// The version number changes when the search criteria changes.  This signals the page to re-build its
        /// cache.
        /// </summary>
        /// <remarks>
        /// This and All properties required to re-establish the page are stored as name / value pairs in
        /// a hash table stored in the session cache under the key Keys.FinancialSummaryPageKey.  
        /// This enables the page to re-establish its state with minimal IO to what it was when
        /// the user last visited it.
        /// </remarks>
        private int SearchCriteriaVersion
        {
            get
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable;
                return (h == null || h[SearchCriteriaVersionKey] == null) ? 0 : (int) h[SearchCriteriaVersionKey];
            }
            set
            {
                Hashtable h = pageCachePolicy.GetCachedObject(PageCacheKey) as Hashtable ?? new Hashtable();
                h[SearchCriteriaVersionKey] = value;
                pageCachePolicy.Cache(PageCacheKey, h);
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Invoked by the download bar when it catches an exception.
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnDownloadFailed(object sender, CommandEventArgs e)
        {
            annunciator.Title = "Following error(s) occurred while downloading";
            annunciator.Message = ExceptionReport.GetExceptionInfo((Exception) e.CommandArgument, false);
        }

        /// <summary>
        /// Handler for the event raised when the FirstPage link in clicked in the Pager control.
        /// Set the current page index to 0, bind the datagrid with data and manage navigation links. To avoid superfluous
        /// data binding activites, no action is taken if the current page index is already 0.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnFirstPage(object sender, CommandEventArgs e)
        {
            CurrentPageIndex = 0;
            LoadDataGrid();
        }

        /// <summary>
        /// Resets the sub-navigation selected link before the header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
            subNavigation.Reset();
            if (detailsSubNavigation.Visible)
            {
                detailsSubNavigation.Reset();
            }
        }

        /// <summary>
        /// Purges the cache before the agreements subnavigation header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnSubNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        /// <summary>
        /// Purges the cache before the agreement details subnavigation header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnDetailsSubNavigate(object sender, CommandEventArgs e)
        {
            PurgeCache();
        }

        /// <summary>
        /// Add the appropriate sort symbol to denote ascending/descending sequence for the current sort column.
        /// This requires us to locate the cell which corresponding to the column within the collection of TableCell
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        protected void OnItemCreated(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Header)
                {
                    BudgetBreakdowns breakdowns = BudgetBreakdowns;
                    Label sortSymbol = new Label();
                    sortSymbol.CssClass = "Sort";
                    sortSymbol.Text = breakdowns.SortAscending ? Constants.SortAscendingText : Constants.SortDescendingText;
                    sortSymbol.Font.Name = Constants.SortSymbolFontName;
                    string sortExpression = breakdowns.SortColumn;

                    foreach (DataGridColumn column in dataGrid.Columns)
                    {
                        if (column.SortExpression == sortExpression)
                        {
                            (e.Item.Cells[dataGrid.Columns.IndexOf(column)]).Controls.Add(sortSymbol);
                            break;
                        }
                    }
                }
                else if (e.Item.ItemType == ListItemType.Footer)
                {
                    int cellCount = e.Item.Cells.Count;
                    for (int i = 0; i < cellCount - 1; i++)
                    {
                        e.Item.Cells.RemoveAt(0);
                    }
                    e.Item.Cells[0].ColumnSpan = cellCount;
                }
                else if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
                {
                    e.Item.EnableViewState = false;
                }
            }
            catch (Exception ex)
            {
                annunciator.Title = "Following error(s) occurred during item creation";
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// Add the Full Title tool tip that gets displayed when a mouse over occurs on a cell in the Project Title column.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    decimal amount = Math.Round(Convert.ToDecimal(e.Item.Cells[1].Text), 1);
                    if (amount < 0)
                    {
                        e.Item.Cells[1].CssClass = "DataGridNegativeCurrencyItem";
                    }
                    e.Item.Cells[1].Text = amount.ToString("c", Helper.ZeroDecimals());
                }
                else if (e.Item.ItemType == ListItemType.Footer)
                {
                    e.Item.Cells[0].Text =
                        string.Format("Category: {0}  |  {1}Total Budget: {2}",
                            BudgetBreakdowns.CategoryName,
                            (BudgetBreakdowns.AccountNumber != string.Empty)
                                ? string.Format("Account Number: {0}  |  ", BudgetBreakdowns.AccountNumber)
                                : string.Empty,
                            BudgetBreakdowns.TotalBudgetAmount.ToString("c", Helper.ZeroDecimals()));
                }
            }
            catch (Exception ex)
            {
                annunciator.Title = "Following error(s) occurred during item data binding";
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// Handler for the event raised when the LastPage link in clicked in the Pager control.
        /// Set the current page index to one less than the total page count (index is 0-based), bind the datagrid with
        /// data and manage navigation links. To avoid superfluous data binding activites, no action is taken if the current
        /// page index is already corresponding to the last page.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnLastPage(object sender, CommandEventArgs e)
        {
            CurrentPageIndex = pagerAboveDatagrid.PageCount - 1;
            LoadDataGrid();
        }

        /// <summary>
        /// Initialize the bread crumb control, set the page size for the data grid, and load the data grid with data.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                downloadBar.SQLReportName = "BudgetBreakdown";
                annunciator.Message = string.Empty;

                if (!IsPostBack)
                {
                    breadCrumb.Add("Budget Breakdown", Settings.GetKeyValue("Other.Agreements.BudgetBreakdownURL", ""),
                        (detailsSubNavigation.Visible) ? 4 : 3);

                    Hashtable h = (Hashtable) pageCachePolicy.GetCachedObject(Keys.IncomingDataKey);
                    if (h != null)
                    {
                        if (h[Keys.CategoryIDKey] != null)
                        {
                            CategoryID = Convert.ToInt32(h[Keys.CategoryIDKey]);
                        }
                        if (h[Keys.AccountNumberKey] != null)
                        {
                            AccountNumber = h[Keys.AccountNumberKey].ToString();
                        }
                        if (h[Keys.BudgetStartDateKey] != null)
                        {
                            BudgetStartDate = h[Keys.BudgetStartDateKey].ToString();
                        }
                        if (h[Keys.BudgetEndDateKey] != null)
                        {
                            BudgetEndDate = h[Keys.BudgetEndDateKey].ToString();
                        }
                        if (h[Keys.CumulativeKey] != null)
                        {
                            CumLevel = Convert.ToInt32(h[Keys.CumulativeKey]);
                        }

                        pageCachePolicy.UnCache(Keys.IncomingDataKey);
                    }

                    LoadDataGrid();
                }

                if (DetailsFlag == false)
                {
                    subNavigation.EnableOverviewNavigation = true;
                    detailsSubNavigation.Visible = false;
                    subNavigation.SelectedOverviewLink = SubNavigation.BudgetOverviewCommand;
                }

                if (detailsSubNavigation.Visible && DetailsFlag)
                {
                    detailsSubNavigation.SelectedLink = DetailsSubNavigation.BudgetDetailCommand;
                }
            }
            catch (Exception ex)
            {
                annunciator.Title = "Following error(s) occurred during page load";
                annunciator.Message = ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// Purges the cache and sets the correct search context level before the breadcrumb performs a redirect.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnNavigate(object sender, CommandEventArgs e)
        {
            if (((CommandEventArgs) (e.CommandArgument)).CommandName == Convert.ToString((int) SearchCriteria.Level.Summary))
            {
                //set the search context's level to the correct level
                CommonSearchContext searchContext = (CommonSearchContext) cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
                searchContext.CurrentLevel = SearchCriteria.Level.Summary;
            }
            PurgeCache();
        }

        /// <summary>
        /// Handler for the event raised when the NextPage link in clicked in the Pager control.
        /// Increment the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnNextPage(object sender, CommandEventArgs e)
        {
            ++CurrentPageIndex;
            LoadDataGrid();
        }

        /// <summary>
        /// Handler for the event raised when the PreviousPage link in clicked in the Pager control.
        /// Decrement the current page index, bind the datagrid with data and manage navigation links.
        /// </summary>
        /// <param name="sender">Control which rasied the event</param>
        /// <param name="e">Arguments associated with the event</param>
        protected void OnPreviousPage(object sender, CommandEventArgs e)
        {
            --CurrentPageIndex;
            LoadDataGrid();
        }

        /// <summary>
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        protected void OnSort(object source, DataGridSortCommandEventArgs e)
        {
            if (e.SortExpression != string.Empty)
            {
                BudgetBreakdowns.Sort(e.SortExpression);
                CurrentPageIndex = 0;
                LoadDataGrid();
            }
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Load the datagrid with sufficient data for display within one page of the data grid. This is done as follows:
        /// Get the summaries for all agreements that the user has access to. Use that to initialize the data grid and
        /// the pager controls based on the page size of the data grid.
        /// The pagers are made visible only when more than one page of data can be displayed.
        /// If there is no data to display, warn the user via the annunciator.
        /// </summary>
        private void LoadDataGrid()
        {
            try
            {
                BudgetBreakdowns breakdowns = BudgetBreakdowns;
                dataGrid.VirtualItemCount = pagerBelowDatagrid.RecordCount = pagerAboveDatagrid.RecordCount = breakdowns.Count;

                int currentPageIndex = CurrentPageIndex;
                int pageCount = (pagerAboveDatagrid.RecordCount/dataGrid.PageSize) +
                    (((pagerAboveDatagrid.RecordCount%dataGrid.PageSize) == 0) ? 0 : 1);
                if (pageCount == 0)
                {
                    CurrentPageIndex = currentPageIndex = 0;
                }
                else if (currentPageIndex >= pageCount)
                {
                    CurrentPageIndex = currentPageIndex = pageCount - 1;
                }

                pagerBelowDatagrid.PageCount = pagerAboveDatagrid.PageCount = pageCount;
                pagerBelowDatagrid.CurrentPage = pagerAboveDatagrid.CurrentPage = currentPageIndex + 1;

                dataGrid.DataSource = breakdowns.GetBreakdownList(currentPageIndex*dataGrid.PageSize, dataGrid.PageSize);
                dataGrid.DataBind();

                ManagePagination();

                if (!dataGrid.Visible)
                {
                    annunciator.Message = "No budget breakdowns found for the user";
                }
            }
            catch (Exception e)
            {
                pagerBelowDatagrid.Visible = pagerAboveDatagrid.Visible = dataGrid.Visible = false;
                annunciator.Message = ExceptionReport.GetExceptionInfo(e, false);
            }
        }

        /// <summary>
        /// Manage the state of the data grid pagers and the current-page of the data grid. The links on the pager are enabled
        /// or disable as appropriate based on which page is current being displayed.
        /// </summary>
        private void ManagePagination()
        {
            pagerBelowDatagrid.Visible = pagerAboveDatagrid.Visible = dataGrid.Visible = (dataGrid.Items.Count > 0);
            if (dataGrid.Visible)
            {
                int currentPageIndex = CurrentPageIndex;
                dataGrid.CurrentPageIndex = currentPageIndex;

                int startIndex = currentPageIndex*dataGrid.PageSize;

                pagerBelowDatagrid.FirstRecord = pagerAboveDatagrid.FirstRecord = startIndex + 1;
                pagerBelowDatagrid.LastRecord = pagerAboveDatagrid.LastRecord =
                    Math.Min(startIndex + dataGrid.PageSize, dataGrid.VirtualItemCount);

                pagerBelowDatagrid.EnableFirstPage = pagerAboveDatagrid.EnableFirstPage =
                    pagerBelowDatagrid.EnablePreviousPage = pagerAboveDatagrid.EnablePreviousPage =
                        (CurrentPageIndex != 0);

                pagerBelowDatagrid.EnableLastPage = pagerAboveDatagrid.EnableLastPage =
                    pagerBelowDatagrid.EnableNextPage = pagerAboveDatagrid.EnableNextPage =
                        (CurrentPageIndex != (pagerAboveDatagrid.PageCount - 1));
            }
        }

        /// <summary>
        /// Purge the cached BO from the cache and remove its key from the cache.
        /// </summary>
        private void PurgeCache()
        {
            ResultsCache.PurgeObject(cachePolicy);
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Retrieve the prevalent cahce policies and initialize event handlers. On non-postback, retrieve key information
        /// from inter-page context dictionary for later use.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];

            if (!IsPostBack)
            {
                Hashtable dictionary = (Hashtable) pageCachePolicy.GetCachedObject(Keys.IncomingDataKey);
                if (dictionary != null)
                {
                    GLPostAsOfDate = (DateTime) dictionary[InsightUtilities.Constants.GLPostAsOfDateKey];
                    CategoryID = (int) dictionary[Keys.CategoryIDKey];
                    DetailsFlag = (bool) dictionary[Keys.DetailsKey];

                    string selectedBudgetDetailFundNumber = dictionary[Keys.SelectedBudgetDetailFundNumberKey] as String;
                    if (selectedBudgetDetailFundNumber == null || selectedBudgetDetailFundNumber == string.Empty)
                    {
                        FundNumber = (string) dictionary[Keys.FundNumberKey];
                    }
                    else
                    {
                        //we came in from the budget details page and a fund was selected so use that one
                        //remove from the dictionary, and recache the dictionary.
                        FundNumber = selectedBudgetDetailFundNumber;
                        dictionary.Remove(Keys.SelectedBudgetDetailFundNumberKey);
                        pageCachePolicy.Cache(Keys.IncomingDataKey, dictionary);
                    }
                }
            }

            subNavigation.EnableOverviewNavigation = !(detailsSubNavigation.Visible = (FundNumber != null));
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        #endregion
    }
}

// --- EOF ---